package com.shyroke.daydayzhuansvc.service.impl;

import com.querydsl.core.QueryResults;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.shyroke.daydayzhuanapi.dto.AdminProjectPartDto;
import com.shyroke.daydayzhuanapi.dto.AdminProjectPartTypeDto;
import com.shyroke.daydayzhuanapi.entity.ProjectPartEntity;
import com.shyroke.daydayzhuanapi.entity.ProjectPartTypeEntity;
import com.shyroke.daydayzhuanapi.entity.QProjectPartEntity;
import com.shyroke.daydayzhuanapi.entity.QProjectPartTypeEntity;
import com.shyroke.daydayzhuanapi.mapper.ProjectPartMapper;
import com.shyroke.daydayzhuanapi.mapper.ProjectPartTypeMapper;
import com.shyroke.daydayzhuandao.respository.ProjectPartRepository;
import com.shyroke.daydayzhuandao.respository.ProjectPartTypeRepository;
import com.shyroke.daydayzhuansvc.util.Page;
import com.shyroke.daydayzhuansvc.util.TabelData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProjectPartTypeService {

    @Autowired
    private ProjectPartTypeRepository projectPartTypeRepository;
    @Autowired
    private JPAQueryFactory factory;
    @Autowired
    private ProjectPartTypeMapper projectPartTypeMapper;


    public TabelData<AdminProjectPartTypeDto> query(Page page) {
        QProjectPartTypeEntity m = QProjectPartTypeEntity.projectPartTypeEntity;
        JPAQuery<ProjectPartTypeEntity> query = factory.selectFrom(m);
        QueryResults<ProjectPartTypeEntity> queryResults = query
                .offset(PageRequest.of(page.getPage() - 1, page.getLimit()).getOffset()).limit(page.getLimit())
                .orderBy(m.id.desc())
                .fetchResults();

        List<AdminProjectPartTypeDto> list = queryResults.getResults().stream().map(projectPartTypeMapper::entityToAdminDto).collect(Collectors.toList());

        return new TabelData(list,(int)queryResults.getTotal());
    }
}
